package com.mingtu.guards.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureMediaScannerConnection;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.CommonFileAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AddFileDocBean;
import com.mingtu.guards.bean.FileListBean;
import com.mingtu.guards.bean.FileTypeBean;
import com.mingtu.guards.bean.MyFileListBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.ValueCallback;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class FileSubDataActivity extends MyBaseActivity {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.iv_plus)
    ImageView ivPlus;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    private String keyword;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private int PAGE_SIZE = 200;
    private String addFileTypeName;
    private String parentId;
    private String subTypeName;
    private String subTypeId;
    private int documentId;
    private String docUrl;
    private String savePath = PathUtils.getExternalDownloadsPath();
    private String docName = "";
    private String filePath;
    private boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
    private CommonFileAdapter commonFileAdapter;
    private int currentPosition = -1;
    private List<MyFileListBean> fileTypeListBeans = new ArrayList<>();
    private List<MyFileListBean> fileDocListBeans = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_file_sub_data;
    }

    @Override
    protected void initView() {
        super.initView();

    }

    @Override
    protected void initData() {

        parentId = getIntent().getStringExtra("parentId");
        String typeName = getIntent().getStringExtra("typeName");
        if (!StringUtils.isEmpty(typeName)) {
            setModuleTitle(typeName);
        }
        if (!isLeader) {
            ivPlus.setVisibility(View.GONE);
        } else {
            showTopRightImg(R.mipmap.icon_upload_cloud);
        }


        LinearLayoutManager manager = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager);
        recycler.addItemDecoration(new BottomSpaceItemDecoration());
        commonFileAdapter = new CommonFileAdapter();
        if (isOpenLoadAnimation) {
            commonFileAdapter.isFirstOnly(isFirstOnly);
            commonFileAdapter.openLoadAnimation(animationType);
        }
        commonFileAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(commonFileAdapter);

        commonFileAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MyFileListBean listBean = commonFileAdapter.getData().get(position);
                boolean isFolder = listBean.isFolder();
                if (isFolder) {
                    String parentId = listBean.getTypeId();
                    String typeName = listBean.getName();
                    Bundle bundle = new Bundle();
                    bundle.putString("parentId", parentId);
                    bundle.putString("typeName", typeName);
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), FileSubDataActivity.class, bundle);
                } else {
                    onItemClickDoc(listBean);
                }

            }
        });
        commonFileAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                currentPosition = position;
                MyFileListBean listBean = commonFileAdapter.getData().get(position);
                boolean isFolder = listBean.isFolder();
                commonFileAdapter.updateStatus(position);
                if (isFolder) {
                    //长按文件夹
                    subTypeId = listBean.getTypeId();
                    subTypeName = listBean.getName();

                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asCustom(new BottomPopup(ActivityUtil.getTopActivity()))
                            .show();
                } else {
                    //长按文件
                    documentId = listBean.getDocumentId();
                    docUrl = listBean.getUrl();
                    docName = listBean.getName();

                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asCustom(new BottomPopupDoc(ActivityUtil.getTopActivity()))
                            .show();
                }

                return false;
            }
        });

    }

    @Override
    protected void getData() {
        initListener();
        getFileType();
        getFileList(1);
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);

        XXPermissions.with(this)
                // 不适配 Android 11 可以这样写
                .permission(Permission.Group.STORAGE)
                // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            startActivityForResult(intent, 200);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(FileSubDataActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(FileSubDataActivity.this, permissions);
                                                }
                                            }, null, false)
                                    .show();
                        }
                    }
                });


    }

    @OnClick({R.id.iv_plus, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_plus:
                new XPopup.Builder(ActivityUtil.getTopActivity())
                        .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new CenterPopup(ActivityUtil.getTopActivity(), 0))
                        .show();
                break;
            case R.id.tv_search:
                Bundle bundle = new Bundle();
                bundle.putString("parentId", parentId);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), SearchFileActivity.class, bundle);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            File file = UriUtils.uri2File(uri);
            ArrayList<File> files = new ArrayList<>();
            files.add(file);
            uploadFile(files);
        }
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == XXPermissions.REQUEST_CODE) {
//            if (!XXPermissions.isGranted(FileSubDataActivity.this, Permission.WRITE_SETTINGS)) {
//                ToastUtils.showLong("修改系统设置权限获取失败！");
//            }
//
//            if (!XXPermissions.isGranted(FileSubDataActivity.this, Permission.READ_EXTERNAL_STORAGE) ||
//                    !XXPermissions.isGranted(FileSubDataActivity.this, Permission.WRITE_EXTERNAL_STORAGE)) {
//                ToastUtils.showLong("读写权限获取失败！");
//            }
//
//            if (XXPermissions.isGranted(FileSubDataActivity.this, Permission.READ_EXTERNAL_STORAGE) &&
//                    XXPermissions.isGranted(FileSubDataActivity.this, Permission.WRITE_EXTERNAL_STORAGE) &&
//                    XXPermissions.isGranted(FileSubDataActivity.this, Permission.WRITE_SETTINGS)) {
//
//                //如果文件存在
//                if (FileUtils.isFileExists(filePath)) {
//                    openFileReader(filePath);
//                } else {
//                    //文件不存在 ,下载完成之后打开
//                    downloadDocFile();
//                }
//            }
//
//        }
//
//
//    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                commonFileAdapter.getData().clear();
                getFileType();
                getFileList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(fileDocListBeans, PAGE_SIZE);
                    getFileList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 点击文档
     *
     * @param listBean
     */
    private void onItemClickDoc(MyFileListBean listBean) {
        docUrl = listBean.getUrl();
        docName = listBean.getName();
        filePath = savePath + "/" + docName;

        if (StringUtils.isEmpty(docName)) {
            ToastUtils.showLong("文件读取错误！");
            return;
        }

        if (StringUtils.isEmpty(docUrl)) {
            ToastUtils.showLong("文件链接错误！");
            return;
        }

        boolean isHasVideo = PictureMimeType.isUrlHasVideo(docUrl);
        boolean isHasImage = PictureMimeType.isUrlHasImage(docUrl);

        if (isHasVideo) {
            Bundle bundle = new Bundle();
            bundle.putString("vodeoUrl", docUrl);
            bundle.putString("title", docName);
            IntentUtils.getInstance().readyGo(ActivityUtils.getTopActivity(), VideoPlayActivity.class, bundle);
            return;
        }

        if (isHasImage) {
            ArrayList<LocalMedia> pictureMediaList = new ArrayList<>();
            LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(docUrl);
            pictureMediaList.add(localMedia);
            BaseApplication.initPreviewModel().startActivityPreview(0, false, pictureMediaList);
            return;
        }


        XXPermissions.with(FileSubDataActivity.this)
                .permission(Permission.WRITE_SETTINGS)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.WRITE_SETTINGS)) {
                            dealFile();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            ToastUtils.showLong("请手动授予修改系统设置权限");
                            XXPermissions.startPermissionActivity(FileSubDataActivity.this, permissions);
                        } else {

                        }

                    }
                });
    }

    private void dealFile() {
        XXPermissions.with(FileSubDataActivity.this)
                // 不适配 Android 11 可以这样写
                .permission(Permission.Group.STORAGE)
                // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
//                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) || permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
                            //如果文件存在
                            if (FileUtils.isFileExists(filePath)) {
                                openFileReader(filePath);
                            } else {
                                //文件不存在 ,下载完成之后打开
                                downloadDocFile();
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(FileSubDataActivity.this)
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), context.getResources().getString(R.string.text_storage_auth),
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(FileSubDataActivity.this, permissions);
                                                }
                                            }, null, false)
                                    .show();
                        }
                    }
                });
    }

    /**
     * 获取文件类型
     */
    private void getFileType() {
        OkGo.<String>post(MyConstant.POST_FILE_TYPE)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                FileTypeBean fileTypeBean = new FileTypeBean();
                                fileTypeBean = gson.fromJson(result, FileTypeBean.class);
                                List<FileTypeBean.ListBean> dataBeans = fileTypeBean.getList();
                                for (int i = 0; i < fileTypeListBeans.size(); i++) {
                                    commonFileAdapter.remove(i);
                                }
                                fileTypeListBeans.clear();
                                if (dataBeans != null && dataBeans.size() > 0) {
                                    for (int i = 0; i < dataBeans.size(); i++) {
                                        FileTypeBean.ListBean listBean = dataBeans.get(i);
                                        String id = listBean.getParentId();
                                        String name = listBean.getName();
                                        String typeId = listBean.getTypeId();
                                        if (id.equals(parentId)) {
                                            MyFileListBean myFileListBean = new MyFileListBean();
                                            myFileListBean.setFolder(true);
                                            myFileListBean.setName(name);
                                            myFileListBean.setStatus(false);
                                            myFileListBean.setTypeId(typeId);
                                            fileTypeListBeans.add(myFileListBean);
                                        }
                                    }
                                    commonFileAdapter.addData(0, fileTypeListBeans);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 获取文件
     * 为了避免分页引起的上传文件的重复显示，此处的PAGE_SIZE设置为了200，为了一次请求全部数据
     */
    private void getFileList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", PAGE_SIZE);
        hashMap.put("name", keyword);
        hashMap.put("typeId", parentId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_TYPE_SON)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            FileListBean fileListBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                fileListBean = new FileListBean();
                                fileListBean = gson.fromJson(result, FileListBean.class);
                                List<FileListBean.PageBean.ListBean> dataBeans = fileListBean.getPage().getList();

                                if (dataBeans != null && dataBeans.size() > 0) {

                                    isLoadMore = dataBeans.size() > 0 && dataBeans.size() % PAGE_SIZE == 0 ? true : false;
                                    List<MyFileListBean> myFileListBeans = new ArrayList<>();
                                    for (int i = 0; i < dataBeans.size(); i++) {
                                        FileListBean.PageBean.ListBean listBean = dataBeans.get(i);
                                        String name = listBean.getName();
                                        String createTime = listBean.getCreateTime();
                                        String url = listBean.getUrl();
                                        int fileSize = listBean.getFileSize();
                                        int documentId = listBean.getDocumentId();

                                        MyFileListBean myFileListBean = new MyFileListBean();
                                        myFileListBean.setName(name);
                                        myFileListBean.setCreateTime(createTime);
                                        myFileListBean.setFileSize(fileSize);
                                        myFileListBean.setDocumentId(documentId);
                                        myFileListBean.setStatus(false);
                                        myFileListBean.setFolder(false);
                                        myFileListBean.setUrl(url);

                                        myFileListBeans.add(myFileListBean);
                                    }

                                    if (currentPage == 1) {
                                        fileDocListBeans.clear();
                                    }
                                    fileDocListBeans.addAll(myFileListBeans); //用来进行上拉加载操作的逻辑
                                    commonFileAdapter.addData(myFileListBeans);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 上传文件
     */
    private void uploadFile(ArrayList<File> files) {
        OkGo.<String>post(MyConstant.POST_UPLOAD_FILE)
                .tag(this)
                .params("attachParams", parentId)
                .addFileParams("file", files)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoadingDialog();
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            AddFileDocBean addFileDocBean = new AddFileDocBean();
                            addFileDocBean = gson.fromJson(result, AddFileDocBean.class);
                            String msg = addFileDocBean.getMsg();
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong(getResources().getString(R.string.text_upload_success));
                                AddFileDocBean.DataBean dataBean = addFileDocBean.getData();

                                String name = dataBean.getName();
                                String createTime = dataBean.getCreateTime();
                                String url = dataBean.getUrl();
                                int fileSize = dataBean.getFileSize();
                                int documentId = dataBean.getDocumentId();

                                MyFileListBean myFileListBean = new MyFileListBean();
                                myFileListBean.setName(name);
                                myFileListBean.setCreateTime(createTime);
                                myFileListBean.setFileSize(fileSize);
                                myFileListBean.setDocumentId(documentId);
                                myFileListBean.setStatus(false);
                                myFileListBean.setFolder(false);
                                myFileListBean.setUrl(url);

                                commonFileAdapter.addData(myFileListBean);

                            } else {
                                ToastUtils.showLong(getResources().getString(R.string.text_upload_fail));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        hideLoadingDialog();
                        String result = response.body();
                        ToastUtils.showLong(result);
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        MyLogUtil.e("uploadProgress", "uploadProgress: " + progress);
                        showLoadingDialog("上传中...");
                    }
                });
    }

    /**
     * 新增文件分类
     */
    private void addFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", addFileTypeName);
        hashMap.put("parentId", parentId);

        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_ADD_TYPE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            addFileTypeName = null;
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                getFileType(); // 刷新文件列表
                            }
                        }
                    }
                });
    }

    /**
     * 删除分类
     */
    private void deleteFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("typeId", Integer.parseInt(subTypeId));
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_DELETE_TYPE + "/" + subTypeId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            subTypeId = null;
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("删除成功！");
                                commonFileAdapter.remove(currentPosition);
                            }
                        }
                    }
                });
    }

    /**
     * 删除文件
     */
    private void deleteFileDoc() {
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(documentId);
        OkGo.<String>post(MyConstant.POST_FILE_DELETE_DOC)
                .tag(this)
                .upJson(jsonArray)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            documentId = 0;
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("删除成功！");
                                commonFileAdapter.remove(currentPosition);
                            }
                        }
                    }
                });
    }

    /**
     * 修改分类
     */
    private void updateFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", addFileTypeName);
        hashMap.put("typeId", subTypeId);
        hashMap.put("parentId", parentId); //已经分类传parentId
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_UPDATE_TYPE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("重命名成功！");
                                MyFileListBean myFileListBean = commonFileAdapter.getData().get(currentPosition);
                                myFileListBean.setName(addFileTypeName);
                                commonFileAdapter.getData().set(currentPosition, myFileListBean);
                                commonFileAdapter.notifyItemChanged(currentPosition);

                                addFileTypeName = null;
                                subTypeId = null;
                            }
                        }
                    }
                });
    }

    /**
     * 下载文件
     */
    private void downloadDocFile() {
        if (StringUtils.isEmpty(docUrl)) {
            ToastUtils.showLong("未获取到文件链接！");
            return;
        }
        GetRequest<File> request = OkGo.<File>get(docUrl);
        DownloadTask downloadTask = OkDownload.request(docUrl, request);
        downloadTask.folder(savePath);
        downloadTask.fileName(docName);
        downloadTask.register(new DownloadListener(docUrl) {
            @Override
            public void onStart(Progress progress) {
                showDownLoadDialog();
                //howLoadingDialog("下载中...");
            }

            @Override
            public void onProgress(Progress progress) {

            }

            @Override
            public void onError(Progress progress) {
                hideDownLoadDialog();
                ToastUtils.showLong(getResources().getString(R.string.text_download_fail));
            }

            @Override
            public void onFinish(File file, Progress progress) {
                //扫描更新媒体库
                hideDownLoadDialog();
//                MediaScannerConnection.scanFile(context, new String[]{savePath}, null, null);
                new PictureMediaScannerConnection(context, file.getAbsolutePath(), () -> {
                });
                ToastUtils.showLong(getResources().getString(R.string.text_download_success));

                openFileReader(filePath);

                docUrl = null;
                docName = null;

            }

            @Override
            public void onRemove(Progress progress) {

            }
        });
        downloadTask.save();
        downloadTask.start();
    }

    /**
     * 中间弹出的pop
     */
    public class CenterPopup extends CenterPopupView {

        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.edit_file_name)
        EditText editFileName;
        @BindView(R.id.but_commit)
        Button butCommit;
        int type = 0; // 0：是添加文件夹  1：修改文件夹

        public CenterPopup(@NonNull Context context, int type) {
            super(context);
            this.type = type;
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.add_file_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);

            if (type == 0) {
                tvTitle.setText("创建文件夹");
            } else if (type == 1) {
                tvTitle.setText("重命名文件夹");
                editFileName.setText(subTypeName);
                editFileName.setSelection(subTypeName.length());
            }

            addFileTypeName = subTypeName;

            editFileName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    addFileTypeName = MyUtills.getEditText(editFileName);
                    editFileName.setSelection(addFileTypeName.length());
                }
            });


        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            KeyboardUtils.hideSoftInput(ActivityUtil.getTopActivity());
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.but_commit})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.but_commit:
                    KeyboardUtils.hideSoftInput(this);
                    if (StringUtils.isEmpty(addFileTypeName)) {
                        ToastUtils.showLong("请输入文件夹名称~");
                        return;
                    }
                    dismiss();
                    if (type == 0) {
                        addFileType();
                    }
                    if (type == 1) {
                        updateFileType();
                    }
                    break;

            }
        }
    }

    /**
     * 底部弹出的pop
     */
    public class BottomPopup extends BottomPopupView {

        @BindView(R.id.tv_rename)
        TextView tvRename;
        @BindView(R.id.tv_delete)
        TextView tvDelete;

        public BottomPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.layout_file_operate;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);
        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            commonFileAdapter.resetStatus(currentPosition);
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.tv_rename, R.id.tv_delete})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.tv_rename:
                    dismiss();
                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asCustom(new CenterPopup(ActivityUtil.getTopActivity(), 1))
                            .show();
                    break;
                case R.id.tv_delete:
                    dismiss();
                    XPopup.setPrimaryColor(getResources().getColor(com.mingtu.center.R.color.red_fc));
                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), "确定要删除文件夹吗？",
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            deleteFileType();
                                        }
                                    }, null, false)
                            .show();

                    break;
            }
        }
    }


    /**
     * 底部弹出的pop
     */
    public class BottomPopupDoc extends BottomPopupView {

        @BindView(R.id.tv_down)
        TextView tvDown;
        @BindView(R.id.tv_delete)
        TextView tvDelete;

        public BottomPopupDoc(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.layout_doc_operate;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);
        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            commonFileAdapter.resetStatus(currentPosition);
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.tv_down, R.id.tv_delete})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.tv_down:
                    dismiss();
                    if (!StringUtils.isEmpty(docUrl)) {
                        downloadDocFile();
                    } else {
                        ToastUtils.showLong("文件下载地址有误哦~");
                    }
                    break;
                case R.id.tv_delete:
                    dismiss();
                    XPopup.setPrimaryColor(getResources().getColor(com.mingtu.center.R.color.red_fc));
                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), "确定要删除文件吗？",
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            deleteFileDoc();
                                        }
                                    }, null, false)
                            .show();

                    break;
            }
        }
    }

    /**
     * 打开下载的文件
     */
    private void openFileReader(String filePath) {
        HashMap<String, String> params = new HashMap<>();
        params.put("local", "true");
        try {
            JSONObject Object = new JSONObject();
            Object.put("pkgName", getApplicationContext().getPackageName());
            params.put("menuData", Object.toString());
            QbSdk.getMiniQBVersion(FileSubDataActivity.this);
            int ret = QbSdk.openFileReader(FileSubDataActivity.this, filePath, params, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                    MyLogUtil.e("testest", "====**====" + s);

                }
            });
            //1：用QQ浏览器打开 2：用MiniQB打开 3：调起阅读器弹框 -1：filePath为空 打开失败 -5：高版本Android没有定义ContentProvider -6：打开apk类型的文件uri解析为空 -7：fileType为空
            switch (ret) {
                case -1:
                    ToastUtils.showLong("打开失败，文件地址有误!");
                    break;
                case -5:
                    ToastUtils.showLong("高版本Android没有定义ContentProvider!");
                    break;
                case -6:
                    ToastUtils.showLong("打开apk类型的文件uri解析为空!");
                    break;
                case -7:
                    ToastUtils.showLong("fileType为空!");
                    break;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}